package route

import (
	"fmt"
	"log"
	"net/http"

	"poker/controller"
	"poker/env"
	"poker/middleware"
	"poker/ws"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/nlh1996/utils"
)

// Init .
func Init() {
	gin.SetMode(env.GlobalData.Server.Mode)
	router := gin.New()
	//router.Use(middleware.TLSHandler())
	router.Use(gin.Logger())
	router.Use(middleware.CrossDomain())
	router.SetTrustedProxies([]string{"127.0.0.1"})
	router.GET("/", Handler)

	api := router.Group("api/v1")
	{
		// 支付相关接口
		api.GET("/api/pay/callback", controller.TestPaySuccessCallback)
		api.POST("/api/pay/callback", controller.PaySuccessCallback)
		api.POST("/api/pay/order", controller.CreateOrder)
		api.GET("/api/pay/orders", controller.GetOrders)
		api.POST("/api/pay/order_resend", controller.ReSendOrder)
		api.POST("/api/pay/order_finish", controller.OrderFinish)

		// 登录
		api.POST("login", controller.GetUserInfo)
		api.POST("get_client_config_version", controller.GetClientConfigVersion)
		api.POST("get_client_config_file_path", controller.GetClientConfigFilePath)

		api.POST("check_token_is_valid", controller.CheckTokenIsValid)
		// api.POST("/api/pay/get_balance", controller.GetBalance)
		// api.GET("/api/pay/queryPayState", controller.QueryPayState)
	}

	router.Run(":" + utils.IntToString(env.GlobalData.Server.Port))
}

var (
	upGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	router *ws.Router
)

func init() {
	router = ws.NewRouter()

	router.AddRouter(Login, controller.Login)
	router.AddRouter(ConfigItem, controller.GetItemConfig)

	// 快速开始
	router.AddRouter(QuickStart, controller.QuickStart)

	// 赛季相关
	router.AddRouter(MatchList, controller.MatchList)
	// router.AddRouter(TableRoomCreate, controller.CreateTableRoom)
	// 坐下
	//router.AddRouter(SitDstartCountDownown, false, controller.sitDown)
	// 起立
	// router.AddRouter(LeaveTable, controller.leaveTable)
	// router.AddRouter(TableRoomKick, controller.tableRoomKick)
	// // 开始准备
	// router.AddRouter(Ready, controller.ready)
	// // 取消准备
	// //router.AddRouter(Unready, true, controller.unready)
	// //发送牌局
	// router.AddRouter(TableOutCard, controller.outCard)
	// router.AddRouter(TableChangeCard, controller.tableChangeCard)
	// //托管
	// router.AddRouter(TableTuoGuanCancel, controller.tuoGuanCancel)
	// //聊天
	// router.AddRouter(TableChat, controller.tableChat)
	// //解散桌子
	// router.AddRouter(TableDissolve, controller.dissolve)
	// router.AddRouter(TablePayCardReturn, controller.payCardReturn)
	// router.AddRouter(TablePayCard, controller.payCard)
	// router.AddRouter(TableRoomSwapSeat, controller.tableRoomSwapSeat)

	// router.AddRouter(TableRoomDismiss, controller.tableRoomDismiss)
	// router.AddRouter(TableRoomExtendPlay, controller.tableRoomExtendPlay)

	// router.AddRouter(TableRoomDismissAgree, controller.tableRoomDismissAgree)
	// router.AddRouter(TableRoomExtendPlayAgree, controller.tableRoomExtendPlayAgree)
	// router.AddRouter(TableRoomSwapSeatAgree, controller.tableRoomSwapSeatAgree)

	// router.AddRouter(ITableReConnect, controller.TableReconnect)
	// router.AddRouter(IMatchCreateTable, controller.icreateMathTable)
	// router.AddRouter(IMatchCloseTable, controller.iMatchCloseTable)
	// router.AddRouter(IBeanTableStart, controller.iBeanTableStart)
	// router.AddRouter(ITableRoomEnter, controller.iEnterTableRoom)
	// router.AddRouter(IMatchDismiss, controller.IMatchDismiss)
	// router.AddRouter(ILiveDismiss, controller.ILiveDismiss)

	// //router.AddRouter(IDrillJoin, false, controller.IDrillJoin)
	// //router.AddRouter(IBeanRestart, false, controller.IBeanRestart)
	// router.AddRouter(IGoldTableStart, controller.iGoldTableStart)

	// router.AddRouter(ILive, controller.iLive)
	// router.AddRouter(IWatchConnectOrDiss, controller.watchPlayerConnectOrDiss)

	// router.AddRouter(TableUserOp, controller.saveTableUserOp)
	// router.AddRouter(TableUserShuffleCards, controller.saveTableUserShuffleCards)
}

// Handler .
func Handler(c *gin.Context) {
	// 验证连接安全
	token := c.Query("token")
	// if err := validateToken(token); err != nil {
	// 	return
	// }
	uid := c.Query("uid")
	// 升级get请求为webSocket长连接
	connection, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	fmt.Printf("ws connected, token: %s, uid: %s\n", token, uid)
	conn, err := ws.NewConnection(connection, router, token, uid)
	if err != nil {
		connection.WriteMessage(websocket.TextMessage, []byte(err.Error()))
		return
	}
	// info.SetPlayerNum(1)
	conn.Start()
}
